<!--客户端  vue+ js      需要npm install qiniu-js-->
<template>

 <div>
        <van-overlay :show="show" @click="show = false">
            <div class="wrapper" @click.stop>
                <div class="block">
                    <div class="uploadWorks">
                        <van-row type="flex" justify="space-between" class="head">
                          <van-col @click="tankuang">
                            <img src="http://qxkmdhmin.hn-bkt.clouddn.com/guanbi.png" alt="" class="ximg"/>
                          </van-col>
                          <van-col>
                            <h2 class="publish" @click="publish">上传</h2>
                          </van-col>
                        </van-row>
                        <van-uploader
                          v-model="fileList"
                          multiple
                          :max-count="9"
                          :after-read="afterRead"
                        />
                      </div>
                </div>
            </div>
        </van-overlay>
    </div>
  
</template>


<script>
import Vue from "vue";
import { Toast } from "vant";
import { duration } from "moment";
import * as qiniu from "qiniu-js";

Vue.use(Toast);
export default {
  data() {
    return {
       show:'',
      fileList: [],
      imgStr: "",    //图片区域
      message: "",   //文字描述区域
      checked: false,
    };
  },
  methods: {
    afterRead(file) {
      //console.log(this.fileList);
    },
    tankuang() {
      this.$dialog
        .confirm({
          message: "确定要放弃本次编辑？",
        })
        .then(() => {
          this.$router.push("/mypage");
        })
        .catch(() => {
          this.$router.push("/mypage");
          // on cancel
        });
    },

    publish() {
      //图片区域上传到七牛云
      this.fileList.forEach((item,i) => {   //遍历fileList
        let fl = item.file; //格式是File类型
        // console.log(fl);
        const putExtra = {};
        const config = {
          useCdnDomain: true,
          region: qiniu.region.z0, //要根据自己所在的区域进行更改，可能是z0,也可能是z1,z2
        };
        this.axios.get("/user/uploadToken").then((res) => {
          const token = res.data.token; //token值来自后端接口
          const timestamp = new Date().getTime(); //添加时间戳，保证图片名不重复
          const observable = qiniu.upload(fl,
            timestamp + fl.name,
            token,
            putExtra,
            config
          );
          let that = this;
          const observer = {
            next(res) {},
            error(err) {},
            complete(res) {    //异步任务
              // console.log(res.key);
              if (i != that.fileList.length - 1) {   //如果不是最后一张图
                that.imgStr +=
                  "http://www.zlllcy.com/" + res.key + ",";
              }
               else {  //如果是最后一张图
                  that.imgStr += "http://www.zlllcy.com/" + res.key;
                  // console.log(that.imgStr);
                  //  console.log(123)
                  //   console.log(this)
                    // alert(that.$store.state.uid),
                    window.sessionStorage.setItem('img',that.imgStr),
                      that.axios.post(
                      "/user/upavator",
                      `aa=${window.sessionStorage.getItem('img')}&id=${that.$store.state.uid}`
                    )
                    .then((res) => {
                      if (res.data.code == 200) {
                        Toast.success({
                          message: "上传成功",
                          duration: "1000",
                        });
                        //加上这个一次性定时器使得跳转页面在 Toast之后执行
                        setTimeout(() => {
                          that.$router.push("/mypage");
                        }, 1000);
                      }
                    })
                    
                  //文字描述区域
                  if (!that.message.trim()) {
                    //如果未输入文字描述，则跳出函数
                    return; //函数是通过return来跳出, 循环是通过break来跳出
                  }
                  //上传时间
                  let date = new Date().toLocaleDateString(); //转为本地字符串
                  // console.log(1111);
                }
              },
            };
            const subscription = observable.subscribe(observer); // 上传开始
        });
      });
    },
  },
};
</script>

<style lang="scss"  scoped>
.wrapper {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
  }

  .block {
    width: 13rem;
    height: 12rem;
    background-color: #fff;
    border-radius: .3125rem;
  }
  .ximg{
    font-size: .75rem;
  }
.uploadWorks {
  padding: 0.8rem;
  .head {
    margin-bottom: 1rem;
    .publish {
      font-size: 16px;
      color: gray;
    }
  }
}
</style>